import numpy as np

import urlearning.DimacsGraph as DimacsGraph

# This class implements a reader for a restricted form of the DIMACS graph format.
# This implementation assumes indices are base-0.

# The rows of the adjacency matrix correspond to variables, and the columns give
# the parents for that variable.

class DimacsGraphReader:

    def __init__(self):
        self.stream = None
        self.graph = None

    # If directed is True, then edges will be added in both directions.
    # Otherwise, only the specified direction is added.
    def read(self, filename, weighted=False, directed=False):
        self.stream = open(filename)

        for line in self.stream:
            # check if this defines the number of nodes
            if line.startswith("p"):
                s = line.strip().split(" ")
                n = int(s[1])
                self.graph = DimacsGraph.DimacsGraph(n, weighted, directed)

            # check if this defines an edge
            if line.startswith("e"):

                s = line.strip().split(" ")
                source = int(s[1])
                destination = int(s[2])
                
                # mild error checking
                if self.graph == None:
                    raise Exception("The \"p\" line must precede \"e\" lines in the DIMACS file.")

                if len(self.graph) < source or len(self.graph) < destination:
                    raise Exception("Line: '{}' includes a node index which exceeds the values specified in the \"p\" line.".format(line))
                
                weight = 1
                if weighted:
                    weight = float(s[3])

                self.graph.addEdge(source, destination, weight)

        self.stream.close()
        return self.graph
